package controller

import (
	"ginWork/global"
	"ginWork/pkg"
	"ginWork/types"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"time"
)

func UserLogin(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")

	user := types.User{
		Username: username,
		Password: password,
	}

	//global.Db.Table("user").Where("username = ?", user.Username).Update("password", user.Password)
	global.Db.Table("user").Where("username = ?", user.Username).First(&user)

	if user.ID == 0 {
		c.JSON(http.StatusOK, gin.H{"code": "-1"})

		return

	}

	if user.Password != password {
		c.JSON(http.StatusOK, gin.H{"code": "-2"})

		return

	}

	token, err := pkg.GetJwtToken("token2205aaaaaaaaaaaahhh", time.Now().Unix(), 86400, strconv.Itoa(int(user.ID)))
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": "-3"})

		return
	}

	c.JSON(http.StatusOK, gin.H{"code": "0", "login": user, "token": token})

}

func UserAdd(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	Age := c.PostForm("Age")
	Sex := c.PostForm("Sex")
	Address := c.PostForm("Address")
	Phone := c.PostForm("Phone")

	age, _ := strconv.Atoi(Age)
	sex, _ := strconv.Atoi(Sex)

	user := types.User{
		Username: username,
		Password: password,
		Age:      age,
		Sex:      sex,
		Address:  Address,
		Phone:    Phone,
	}

	global.Db.Table("user").Create(&user)

	c.JSON(http.StatusOK, gin.H{"code": "0", "add": user})

}
